// +----------------------------------------------------------------------
// | CmsWing [ 美业管理系统 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016 psi All rights reserved.
// +----------------------------------------------------------------------
// | Author: huang <2374266244@qq.com>
// +----------------------------------------------------------------------
'use strict';

export default class extends think.Controller {
  /**
   * index action
   * @return {Promise} []
   */
  // 获取分店项目数据
  async getSubjectListAction() {
    const filter = this.get();
    const where = {};
    where['ss.isdisable'] = 0;
    where['ss.shopid'] = filter.shopid;
    if (filter.search) {
      where['s.name'] = ['like', '%' + filter.search + '%'];
    }
    const list = await this.model('or_shop_subject')
      .alias('ss')
      .field('ss.*, s.name, s.remarks, s.thumbnail')
      .join('think_or_subject s on ss.subjectid = s.id')
      .where(where)
      .select();
    return this.json(list);
  }

  /*
   * @desc 获取单个项目的信息
   * @return {object} 项目信息
   */
  async getSubjectInfoAction() {
    const id = this.get().id;
    const info = await this.model('or_shop_subject')
      .alias('ss')
      .field('ss.*, s.name, s.remarks, s.thumbnail, s.banner, s.desc')
      .join('think_or_subject s on ss.subjectid = s.id')
      .where({'ss.id': id})
      .find();
    return this.json(info);
  }

  /*
   * @desc 获取项目列表（按照项目分类排序）
   * @return {object} 项目信息
   */
  async getSubjectListByTypeAction() {
    const filter = this.get();
    const where = {};
    where['ss.isdisable'] = 0;
    where['ss.shopid'] = filter.shopid;
    const res = await this.model('or_shop_subject')
      .alias('ss')
      .field('s.id, s.name, sc.name as categoryname, s.categoryid')
      .join('think_or_subject s on ss.subjectid = s.id')
      .join('think_or_subjectcategory sc on s.categoryid = sc.id')
      .where(where)
      .select();
    // 返回指定数据格式
    const backarr = [];
    if (res.length) {
      res.forEach(row => {
        const key = this.inarray(row.categoryid, backarr);
        if (key > -1) {
          backarr[key]['child'].push(row);
        } else {
          const a = {
            categoryid: row.categoryid,
            categoryname: row.categoryname,
            child: []
          };
          a.child.push(row);
          backarr.push(a);
        }
      });
    }
    return this.json(backarr);
  }

  inarray(id, arr) {
    let num = -1;
    arr.forEach((row, key) => {
      if (row.categoryid === id) {
        num = key;
      }
    });
    return num;
  }
}
